#include "lua_log.h"

#include <memory>
#include <cstring>

#include "log_msg.h"
#include "sunnet.h"

LuaLog::LuaLog(/* args */)
{
}

LuaLog::~LuaLog()
{
}

int LuaLog::LogNative(lua_State *L, LogMsg::EType log_type){
    // 参数总数
    int num = lua_gettop(L);

    // 参数1:service id
    if(lua_isinteger(L, 1) == 0) {
        return 0;
    }
    int source = lua_tointeger(L, 1);

    // 参数2:log的内容
    if(lua_isstring(L, 2) == 0){
        return 0;
    }

    size_t len = 0;
    const char *buff = lua_tolstring(L, 2, &len);
    char * newstr = new char[len];
    memcpy(newstr, buff, len);

    auto msg= std::make_shared<LogMsg>();
    msg->SetType(BaseMsg::MsgType::LOG);
    msg->SetSource(source);
    msg->SetBuff(newstr);
    msg->SetSize(len);
    msg->SetLogType(log_type);
    Sunnet::GetInstance().SendMsg2LogService(msg);
    
    return 1;
}

void LuaLog::Register(lua_State *L){
    static luaL_Reg lualibs[] = {
        { "LogInfo", LogInfo },
        { "LogDebug", LogDebug },
        { "LogWarn", LogWarn },
        { "LogError", LogError },
        { NULL, NULL }
    };
    luaL_newlib(L, lualibs);
    lua_setglobal(L, "Lua2CppLog");
}

int LuaLog::LogInfo(lua_State *L){
    return LogNative(L, LogMsg::EType::EINFO);
}
int LuaLog::LogDebug(lua_State *L){
    return LogNative(L, LogMsg::EType::EDEBUG);
}
int LuaLog::LogWarn(lua_State *L){
    return LogNative(L, LogMsg::EType::EWARN);
}
int LuaLog::LogError(lua_State *L){
    return LogNative(L, LogMsg::EType::EERROR);
}